package main

import (
	"fmt"
	"gitee.com/liuziloong/ga1400gateway/config"
	_ "gitee.com/liuziloong/ga1400gateway/routers"
	"gitee.com/liuziloong/ga1400gateway/tools/logs"
	"github.com/astaxie/beego"
	"github.com/kqbi/service"
	"os"
	"time"
)

type program struct {
	exit chan bool
}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

func (p *program) run() {
	logs.BeeLogger.Info("%s Service Start!!!", config.ServiceName)
	fmt.Printf("%s %s Service Start!!!\n", time.Now().Format("2006-01-02 15:04:05"), config.ServiceName)

	beego.Run()
	return
}

func (p *program) Stop(s service.Service) error {
	logs.BeeLogger.Info("%s Service Stop!!!", config.ServiceName)
	fmt.Printf("%s %s Service Stop!!!\n", time.Now().Format("2006-01-02 15:04:05"), config.ServiceName)
	close(p.exit)
	if service.Interactive() {
		os.Exit(0)
	}
	return nil
}

func main() {
	svcConfig := &service.Config{
		Name:        config.ServiceName, //服务显示名称
		DisplayName: config.ServiceName, //服务名称
		Description: config.ServiceName, //服务描述
	}

	prg := &program{
		exit: make(chan bool),
	}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		logs.PanicLogger.Fatalln("service.New() error: ", err)
	}

	if len(os.Args) > 1 {
		//install, uninstall, start, stop 的另一种实现方式
		err = service.Control(s, os.Args[1])
		if err != nil {
			logs.PanicLogger.Fatalln(err)
		}
		return
	}

	err = s.Run()
	if err != nil {
		logs.PanicLogger.Fatalln(err)
	}
}
